在Hooks出來以後其實state似乎可以不用學,hooks完全取代了,但還是學一下他的原理,這樣比較好記
import React, { Component } from 'react'
export default class App2 extends Component {
state = {
gonum : 0
}
goClick(e){
this.setState({
gonum : this.state.gonum+1
})
}
render() {
return (
<div>
<p>{ this.state.gonum }</p>
<button onClick={this.goClick.bind(this)}>點我</button>
</div>
)
}
}
import React, { useState } from 'react'
export default function App3() {
const [gonum, goClick] = useState(0);
return (
<div>
<p>{gonum} </p>
<button onClick={() => goClick(gonum + 1)}>點我</button>
</div>
)
}
這邊hooks我新創了一個檔案App3.js來寫,你會發現它的寫法簡潔很多,原本class XXXX extends Component,直接用function函數來取代,事件也不用在加一推this。
把上章寫的內容都改成hooks,不知道有沒有更好的寫法
import React, { Component } from 'react'
export default class App2 extends Component {
state = {
gonum : 0,
gonoyes:false
}
goClick(e){
this.setState({
gonum : this.state.gonum+1 ,
gonoyes : !this.state.gonoyes
})
}
render() {
return (
<div>
<p>{ this.state.gonum }</p>
<button onClick={this.goClick.bind(this)}>{this.state.gonoyes ? 'No' : 'Yes'}</button>
</div>
)
}
}
import React, { useState } from 'react'
export default function App3() {
const [gonum, gocnum] = useState(0);
const [gotext, gonoyes] = useState(false);
const goClick=()=>{
gocnum(gonum+1);
gonoyes(!gotext);
}
return (
<div>
<p>{gonum} </p>
<button onClick={goClick}>{gotext ? 'No' : 'Yes'}</button>
</div>
)
}